import React, {useState, useEffect} from 'react';
import { Modal, Form, Input, Button, Row, Col, message} from 'antd';
import { FormInstance } from 'antd/lib/form';
import { DeviceGroupListItem } from '../data.d';
import DeviceComponent from './DeviceComponent';
import ParentOrgListComponent from '../../System/components/ParentOrgListComponent';
import { deviceGroupDetail } from '../service';
import styles from '../index.less';

interface CreateFormProps {
    modalVisible: boolean;
    values:DeviceGroupListItem;
    onCancel: () => void;
    onSubmit: (values: DeviceGroupListItem) => void;
}

const formRef = React.createRef<FormInstance>();

const AddDeviceGroup: React.FC<CreateFormProps> = (props) => {
    const [deviceIds, setDeviceIds] = useState([]);
    const [deviceData, setDeviceData] = useState([]);
    const [topOrgId, setTopOrgId] = useState<number>(0);

    const { modalVisible, onSubmit, onCancel, values } = props;
    const [form] = Form.useForm();

    const handleFinish = (values: DeviceGroupListItem ) => {
        values.deviceIds = deviceIds.toString();
        if (onSubmit) {
          onSubmit(values as DeviceGroupListItem);
        }
      };

    //设备列表选择回调
    const deviceSelectChange = (deviceIds:[]) =>{
        setDeviceIds(deviceIds);
    }
    //提交
    const handleUpdate = () => {
        if (!form) return;
        if(deviceIds.length == 0){
            message.warn("请选择设备");
            return;
        }
        form.submit();
    };

    // let deviceData = new Array;
    const groupDetail = async (values:DeviceGroupListItem) => {
        const obj = new Object;
        obj["id"] = values.id;
        new Promise((resolve, reject) => {
            deviceGroupDetail(obj)
              .then((res) => {
                if (res && res.code === 200) {
                    const devices = res.data.devices;
                    if(values.type == "detail"){
                        setDeviceData(JSON.parse(JSON.stringify(devices))) //用于点击详情，存放设备列表数据
                    }
                    const list = [];
                    for(let i in devices){
                        if(devices[i]){
                            const id = devices[i].id;
                            list.push(id);
                        }
                    }
                    if(list.length > 0){
                        setDeviceIds(list);
                    }
                    resolve(true);
                }else {
                  resolve(false);
                }
              })
              .catch((error) => {
                reject(error);
              });
          });
    }

    useEffect(() => {
        if(modalVisible){
            setDeviceIds([]);
            setDeviceData([]);
            if(values && values.id){
                console.log(values.type)
                if(values.type != "add"){
                    groupDetail(values);
                    form.setFieldsValue({
                        "id":values.id,
                        "name":values.name,
                        "orgId":values.orgId,
                        "description":values.description,
                    });
                }
            }else{
               form.resetFields();
            }
        }
        
    },[modalVisible]);

  const renderContent = () => {
    return (
      <>
        <Form ref={formRef} form={form} className={styles.AddDeviceGroup} onFinish={handleFinish}>
            <Row gutter={24}>
                <Col span={12}>
                    <Form.Item name="id" style={{display:"none"}}></Form.Item>
                    <Form.Item 
                        name="name" 
                        label="分组名称"
                        
                        rules={[{ required: values.type=="detail"?false:true, max:16 }]} >
                        {values.type == "detail"? 
                            values.name : <Input placeholder="请输入分组名称" style={{ width: 200 }} />
                        }
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item name="orgId" label="所属机构" rules={[{ required: values.type=="detail"?false:true }]}>
                    {values.type == "detail"? values.orgName:
                        <ParentOrgListComponent 
                            defaultvalue={values?values.orgId:-1}
                            type="orgId"
                            selectChange={(value) => {
                                form.setFieldsValue({"orgId": value});
                                setTopOrgId(value);
                                setDeviceIds([]);
                            }}
                            >
                        </ParentOrgListComponent>
                    }
                    </Form.Item>
                </Col>
            </Row>
            <Row>
                <Col span={24}>
                    <Form.Item 
                        name="description" 
                        className="description" 
                        label="描述"
                        rules={[{ max: 200 }]}
                    >
                        {values.type == "detail"? values?.description : <Input placeholder="描述最多200个字" style={{ width:670 }} />
                        }
                    </Form.Item>
                </Col>
            </Row>
            <Row>
                <Col span={24}>
                    <Form.Item className={values.type=="detail"?"device noprompt":"device"} label="设备选择">     
                        <DeviceComponent
                            planCode=""
                            topOrgId={topOrgId>0?topOrgId:-1}
                            type={values.type}
                            data = {values.type == "detail"?deviceData:[]}
                            deviceIds={deviceIds} 
                            setDeviceIds={(deviceIds)=> {deviceSelectChange(deviceIds)}}
                        />
                    </Form.Item>
                </Col>
            </Row>
        </Form>
      </>
    )}
  return (
    <Modal
      width={960}
      destroyOnClose
      centered
      title={values.type? (values.type=="detail"?"分组详情":"编辑分组"):"新建分组"}
      visible={modalVisible}
      onCancel={() => onCancel()}
      footer={[
          <>
          <Button type="default" onClick={onCancel}>返回</Button>
          {values.type!="detail"? <Button type="primary" onClick={handleUpdate}>保存</Button>:null}
          </>
      ]}
    >
        {renderContent()} 
    </Modal>
  );
};

export default AddDeviceGroup;
